<?php

namespace app\api\controller;

use app\common\controller\ApiController;
use app\common\model\borrow\Record;
use app\common\model\Book;
/**
 * 借书记录接口
 */
class Borrow extends ApiController
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    protected $tableName = 'borrow_record';
    // FIXME: 这里应该为a.id, 因为前端取了id，所以暂时为b.id
    protected $fields = 'b.id, a.user_id,a.book_id,b.title,a.status,a.createtime,a.updatetime,b.stock,b.deletetime';
    protected $fieldsExcept = false;
    protected $onlySelf = true;
    protected $orderBy = 'a.createtime desc';
    protected $conditions = [];
    protected $join = [['fa_book b', 'a.book_id = b.id']];

    protected function processData($method, $data)
    {
        if ($method === 'beforeSave') {
            $bookId = intval($data['book_id']);
            $userId = $this->auth->getUser()->id;

            $book = $this->checkBook($bookId, $userId);
            $data = array_merge($data, $book);
            // 减库存
            $bookModel = new Book();
            $bookModel->incrStock($bookId, -1);

        } else if ($method === 'afterList') {
            foreach ($data as $key => &$record) {
            }
        } else if ($method === 'beforeList') {
            if ($data && isset($data['status']) && $data['status'] == 0) {
                $this->conditions = [
                    'status' => 0,
                ];
            }
        }

        return $data;
    }

    private function checkBook($bookId, $userId)
    {
        if (!$bookId) {
            $this->invalidParam("book_id");
        }
        $recordModel = new Record();
        $bookModel = new Book();
        if ($recordModel->borrowed($bookId, $userId)) {
            $this->fail('这本书借过了', 400);
        }
        $record = $bookModel::find($bookId);
        if (!$record || $record['stock']<1){
            $this->fail('没有库存了', 400);
        }
        return [
            'user_id' => $userId,
            'book_id' => $bookId,
            'status' => 1,
            'createtime' => time()
        ];
    }

    public function returns()
    {
        $bookId = intval($this->request->post('book_id'));
        $userId = $this->auth->getUser()->id;
        $record = new Record();
        if (!$record->borrowed($bookId, $userId)) {
            $this->fail("您没有借这本书或者已经还了", 400);
        }
        $bookModel = new Book();
        $bookModel->incrStock($bookId, 1);
        return $this->success('', $record->returns($bookId, $userId));
    }
}
